import { defineStore } from "pinia";
import { UserInfo, UserState } from "@/stores/interface";
import { Login } from "@/api/interface";
import { loginApi, loginOutApi, personalApi } from "@/api/modules/login";
import { useCookies } from "@vueuse/integrations/useCookies";
import { TOKEN_NAME } from "@/config";
const cookies = useCookies();
export const useUserStore = defineStore({
  id: "userStore",
  state: (): UserState => ({
    token: cookies.get(TOKEN_NAME) || "",
    userInfo: {} as UserInfo
  }),
  getters: {},
  actions: {
    doLong(param: Login.DoLoginFrom): Promise<void> {
      return new Promise((resolve, reject) => {
        loginApi(param)
          .then(({ data }) => {
            const cookies = useCookies();
            cookies.set(TOKEN_NAME, data);
            this.token = data;
            resolve();
          })
          .catch(() => {
            reject();
          });
      });
    },

    logout(): Promise<void> {
      useCookies().remove(TOKEN_NAME);
      this.token = "";
      return new Promise(() => {
        loginOutApi().finally(() => {
          this.userInfo = {} as UserInfo;
        });
      });
    },

    personalInfo() {
      return new Promise((resolve, reject) => {
        personalApi()
          .then(({ data }) => {
            this.userInfo = data;
            resolve(data);
          })
          .catch(() => {
            reject();
          });
      });
    }
  }
});
